package org.papervision3d.materials
{
    import flash.geom.Matrix;
    import flash.display.MovieClip;
    import flash.display.BitmapData;
    import flash.display.IBitmapDrawable;
    import org.papervision3d.objects.DisplayObject3D;
    import flash.display.DisplayObject;
    
    // The MovieMaterial class creates a texture from an existing MovieClip instance.
    // The texture can be animated and/or transparent. Current scale and color values of the MovieClip instance will be used. Rotation will be discarded.
    // The MovieClip's content needs to be top left aligned with the registration point.
    // Materials collects data about how objects appear when rendered.
    public class MovieMaterial extends BitmapMaterial
    {
        // The MovieClip that is used as a texture.
        public var movie:DisplayObject;
    
        // A Boolean value that determines whether the MovieClip is transparent. The default value is false, which is much faster.
        public var movieTransparent:Boolean;
    
        // The MovieMaterial class creates a texture from an existing MovieClip instance.
        // @param    asset           A String that contains an existing MovieClip library id.
        // @param    transparent     [optional] - If it's not transparent, the empty areas of the MovieClip will be of fill32 color. Default value is false.
        // @param    initObject      [optional] - An object that contains additional properties with which to populate the newly created material.
        public function MovieMaterial(asset:*, transparent:Boolean = false, initObject:Object = null)
        {
            super(initBitmap(asset, transparent), initObject);
        }
    
        // Updates animated MovieClip bitmap.
        // Draws the current MovieClip image onto bitmap.
        public override function updateBitmap():void
        {
            var tex:BitmapData = this.bitmap;
            var mov:DisplayObject  = this.movie;
    
            tex.fillRect(tex.rect, this.fillColor);
    
            var mtx:Matrix = new Matrix();
            mtx.scale(mov.scaleX, mov.scaleY);
    
            tex.draw(mov, mtx, mov.transform.colorTransform);
        }
    
        protected override function createBitmap(asset:*):BitmapData
        {
            // Dispose of previous bitmap
            if (this.bitmap) 
                this.bitmap.dispose();
    
            // Create new bitmap
            this.bitmap = new BitmapData(asset.width, asset.height, this.movieTransparent);
    
            // Draw bitmap
            this.movie = asset;
            updateBitmap();
    
            return this.bitmap;
        }
        
        override public function dispose() : void {
        	super.dispose();
        	movie = null;
        }
    
    
        private function initBitmap(asset:*, transparent:Boolean):*
        {
            this.movieTransparent = transparent || false;
    
            return asset;
        }
    }
}
